<?php


class User extends DB{

    protected $hash;
    public function __construct(){
        parent::__construct('f_system_user');
        $this->hash=defined('PASS_HASH')?PASS_HASH:'cms';
    }
    public function login($u,$p){

        $p=$this->encrypt($p);
        $qu=$this->safefilter($u);
        $qp=$this->safefilter($p);

        $r=$this->select(sprintf('`user_name` =  %s  AND  `user_pass` =  %s',$qu,$qp));

        if(empty($r)){
            $this->errorinfo[2]='用户名或密码错误';
            return false;
        }
        $_SESSION['login']=$this->encrypt($u);
        $_SESSION['u']=$u;
        setcookie('u',$_SESSION['login'],time()+3600);
        return true;

    }
    public static  function loginout(){
        $_SESSION['login']=null;
        setcookie('u','',time()-10000);
    }
    public function reg($user,$pass){
        if($this->isexist($user)===true){
            $this->errorinfo[2]='用户名存在';
            return false;
        }
        $param=array();
        $param['user_name']=$user;
        $param['user_pass']=$pass;
        return $this->insert($param);

    }
    public function isexist($u){
        $qu=$this->safefilter($u);
        $r=$this->select(sprintf('`user_name` =  %s',$qu));
        return !empty($r);
    }
    public static function islogin(){


        $islogin=false;
        $enuser=isset($_SESSION['login'])?$_SESSION['login']:'';
        $enuser=$enuser===''?isset($_COOKIE['u'])?$_COOKIE['u']:'':$enuser;


        $ouser=new User();
        $alluser=$ouser->select('','','user_name');
        foreach ($alluser as $user) {
            if($ouser->encrypt($user['user_name'])===$enuser ){
                $_SESSION['u']=$user['user_name'];
                $_SESSION['login']=$enuser;
                $islogin=true;
                break;
            }
        }
        return $islogin;


    }
    public function encrypt($str){
        $token=md5($this->hash);
        $p=sha1($str);
        $newp='';

        for($i=strlen($token)-1;$i>0;$i--){
            $newp.=$token[$i].$p[$i];
        }
        return $newp;
    }
}

